package co.th.bjc.md.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import co.th.bjc.md.dao.CustomerData;
import co.th.bjc.md.dao.Hospital;
import co.th.bjc.md.dao.Person;
import co.th.bjc.md.dao.Province;
import co.th.bjc.md.dao.Region;
import co.th.bjc.md.process.service.CallService;
import co.th.bjc.md.service.interfaces.CustomerDataManageService;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class HospitalManageServlet
 */
public class HospitalManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HospitalManageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		String action = request.getParameter("action")==null?"":request.getParameter("action");
		
		if(action.equals("SEARCH")){
			PrintWriter out = response.getWriter();
			jsonObject = this.getSearchResult(request, response);
			out.print(jsonObject);
		}else if(action.equals("DELETE")){
			// Delete process
			if(this.delete(request, response)){
				PrintWriter out = response.getWriter();
				status = true;
				jsonObject = this.getSearchResult(request, response);
				jsonObject.add(status);
				out.print(jsonObject);
			}
		}else if(action.equals("GETEDIT")){
			PrintWriter out = response.getWriter();
			jsonObject = getEditItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else if(action.equals("GETPROVINCE")){
			PrintWriter out = response.getWriter();
			jsonObject = getProvinceList();
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else if(action.equals("GETPERSON")){
			PrintWriter out = response.getWriter();
			String prefix = request.getParameter("term");
			jsonObject = getPersonList(prefix);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else{
			getServletContext().getRequestDispatcher("/jsp/datamanage/manage_hospital_main.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		try {
			Hashtable multipartParams = HospitalManageServlet.getParamsFromMultipartForm(request);
			Hospital obj = new Hospital();
			Region region = new Region();
			region.setRegionId(BigDecimal.valueOf(Long.parseLong((String)multipartParams.get("ins_region"))));
			obj.setRegion(region);
			
			Province province = new Province();
			province.setProvinceId(BigDecimal.valueOf(Long.parseLong((String)multipartParams.get("ins_province"))));
			obj.setProvince(province);
			
			Person person = new Person();
			person.setPersonCode(BigDecimal.valueOf(Long.parseLong((String)multipartParams.get("ins_president"))));
			obj.setPresident(person);
			
			obj.setAddress((String) multipartParams.get("ins_address"));
			obj.setEmail((String) multipartParams.get("ins_email"));
			obj.setHospitalNameEN((String) multipartParams.get("ins_hospital_name_en"));
			obj.setHospitalNameTH((String) multipartParams.get("ins_hospital_name_th"));
			obj.setHospitalType((String) multipartParams.get("ins_type"));
			obj.setTelephone((String) multipartParams.get("ins_telephone"));
			
			String hospitalCode = (String) multipartParams.get("hospital_code");
			if(!hospitalCode.equals("")){
				obj.setHospitalCode(BigDecimal.valueOf(Long.parseLong(hospitalCode)));
			}
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		
		
	}
	public static Hashtable getParamsFromMultipartForm(HttpServletRequest req) throws FileUploadException {
        Hashtable ret = new Hashtable();
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        for (FileItem item : items) {
            if (item.isFormField()) {
                ret.put(item.getFieldName(), item.getString());
            }
        }
        return ret;
    }
	
	private JSONArray getSearchResult(HttpServletRequest request, HttpServletResponse response) {
		String hospitalName = request.getParameter("srh_hospital_name") == null?"":request.getParameter("srh_hospital_name");
		/* for test */
		List<Hospital> list = new ArrayList<>();
		Hospital obj = new Hospital();
		obj.setHospitalCode(BigDecimal.valueOf(1));
		obj.setHospitalNameTH("วชิระ");
		obj.setHospitalNameEN("Vachira");
		obj.setEmail("vachira@hospital.co.th");
		obj.setTelephone("091-718-9281");
		obj.setHospitalType("Private");
		Province pro = new Province();
		pro.setProvinceNameTH("ภูเก็ต");
		pro.setProvinceNameEn("Phuket");
		obj.setProvince(pro);
		list.add(obj);
		JSONArray jsonObject = JSONArray.fromObject(list);
		/* ---- */
		return jsonObject;
	}
	
	private boolean delete(HttpServletRequest request, HttpServletResponse response){
		BigDecimal id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id")));
		return false;
	}
	
	private JSONArray getEditItem(HttpServletRequest request, HttpServletResponse response){
		BigDecimal id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id")));
		/* for test */
		Hospital obj = new Hospital();
		obj.setHospitalCode(BigDecimal.valueOf(1));
		obj.setHospitalNameTH("วชิระ");
		obj.setHospitalNameEN("Vachira");
		obj.setEmail("vachira@hospital.co.th");
		obj.setTelephone("091-718-9281");
		obj.setHospitalType("Public");
		Person per = new Person();
		per.setPersonCode(BigDecimal.valueOf(1));
		per.setPersonTitle("นพ.");
		per.setPersonFirstName("พิพัฒน์");
		per.setPersonLastName("อรรณพคุณ");
		obj.setPresident(per);
		Province pro = new Province();
		pro.setProvinceId(BigDecimal.valueOf(1));
		pro.setProvinceNameTH("ภูเก็ต");
		pro.setProvinceNameEn("Phuket");
		Region reg = new Region();
		reg.setRegionId(BigDecimal.valueOf(1));
		reg.setRegionNameEN("South");
		reg.setRegionNameTH("ใต้");
		pro.setRegion(reg);
		obj.setAddress("281 ม1 ต.เมือง อ.เมือง จ.ภูเก็ต 89010");
		obj.setProvince(pro);
		/* ---- */
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private JSONArray getProvinceList(){
		List<Province> list = new ArrayList<>();
		Province pro = new Province();
		pro.setProvinceId(BigDecimal.valueOf(1));
		pro.setProvinceNameTH("ภูเก็ต");
		pro.setProvinceNameEn("Phuket");
		list.add(pro);
		Province pro1 = new Province();
		pro1.setProvinceId(BigDecimal.valueOf(2));
		pro1.setProvinceNameTH("สงขลา");
		pro1.setProvinceNameEn("Songkla");
		list.add(pro1);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getPersonList(String prefix){
		List<Person> list = new ArrayList<>();
		Person per = new Person();
		per.setPersonCode(BigDecimal.valueOf(1));
		per.setPersonTitle("นพ.");
		per.setPersonFirstName("พิพัฒน์");
		per.setPersonLastName("อรรณพคุณ");
		list.add(per);
		Person per1 = new Person();
		per1.setPersonCode(BigDecimal.valueOf(2));
		per1.setPersonTitle("มรว.ศ.ดร.นพ.พล.อ.");
		per1.setPersonFirstName("กรพจน์");
		per1.setPersonLastName("อุโฆษกิจ");
		list.add(per1);
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}

}
